package pims;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import db.DBManager;

public class ProductEditServlet extends HttpServlet {
	/* (非 Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		perform(req, resp);
	}

	/* (非 Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		perform(req, resp);
	}

	private void perform(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		String id = req.getParameter("id");

		Connection con = null;
		Statement stm = null;
		ResultSet rs = null;

		ProductRecord rec = new ProductRecord();

		String sql = "select * from products where id = " + id;
		try {
			con = DBManager.getConnection();
			stm = con.createStatement();
			rs = stm.executeQuery(sql);

			if (rs.next()) {
				rec.ResultSetToRecord(rs);
			}
			rs.close();
		}
		catch (SQLException e) {
			rs = null;
			e.printStackTrace();
		}
		finally {
			if (stm != null) {
				try {stm.close();}
				catch (SQLException e) {e.printStackTrace();}
			}
			if (con != null) {
				try {con.close();}
				catch (SQLException e) {e.printStackTrace();}
			}
		}
		req.setAttribute("rec", rec);

		RequestDispatcher dispatcher = req.getRequestDispatcher("edit.jsp");
		dispatcher.forward(req, resp);
	}
}
